﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace Elf.Data.Entity.Management
{
    /// <summary>
    /// The scoped db context manager.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ScopedDbContextManager<T> : DbContextManager<T>, IDisposable
        where T : ContextBase, new()
    {
        private T _dbContext;

        /// <summary>
        /// Returns the DbContext instance that belongs to the current DbContextScope.
        /// If currently no DbContextScope exists, a local instance of an DbContext 
        /// class is returned.
        /// </summary>
        public override T DbContext
        {
            get
            {
                if (DbContextScope<T>.CurrentDbContext != null)
                    return DbContextScope<T>.CurrentDbContext;
                else
                {
                    if (_dbContext == null)
                        _dbContext = new T();

                    return _dbContext;
                }
            }
        }

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // dispose managed resources
                _dbContext.Dispose();
            }
            // free native resources
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}
